import React, { useState } from "react";
import { withRouter } from "react-router-dom";
import { doPost } from "../../utils/upload";
import styles from "./index.module.scss";
import URL from "../../common/urls";
import { pageIndex, pages } from "../../common/routerConfig";
import { loginAuth } from "../../common/auth";

const CODE_ERR_HINT = "验证码有误，请重试";
const PHONE_ERR_HINT = "手机号有误，请重试";
const NULL_HINT = "输入不能为空";

// 最初的登录界面
const Index = (props) => {
  const { history } = props;
  const PHONE_MOD = 0,
    CODE_MOD = 1;

  const [mod, setMod] = useState(PHONE_MOD);

  // 电话号码
  const [phoneNumber, setPhoneNumber] = useState("");

  // 验证码
  const [code, setCode] = useState("");

  const [hint, setHint] = useState("");

  // 发送数据{phone: ...}给服务端
  const handleSendPhone = () => {
    if (phoneNumber !== "") {
      setHint((h) => "");
      doPost(URL.doPhone, { phone: phoneNumber })
        .then(async (resp) => {
          const res = await resp.json();
          // 手机号正确
          if (res && res["state"] === 1) {
            setPhoneNumber((p) => "");
            setMod((s) => CODE_MOD);
          } else {
            setHint((h) => PHONE_ERR_HINT);
          }
        })
        .catch((err) => {
          alert(err);
        });
    } else {
      setHint((h) => NULL_HINT);
    }
  };

  // 发送验证码校验登录
  const handleVerify = () => {
    if (code !== "") {
      doPost(URL.doVerify, { verification: code })
        .then(async (resp) => {
          const res = await resp.json();
          // 验证成功
          if (res && res["state"] === 1) {
            setHint((h) => "");
            loginAuth.doLogin();
            history.push({
              // 跳转到密码设置页面
              pathname: pages[pageIndex.setpwd].path,
              query: {
                firstSet: true,
              },
            });
          } else {
            setHint((h) => CODE_ERR_HINT);
            setCode((c) => "");
          }
        })
        .catch((err) => {
          alert(err);
        });
    } else {
      setHint((h) => NULL_HINT);
    }
  };

  const onClickInput = () => {
    setHint((h) => "");
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>Login</div>
      {mod === PHONE_MOD ? (
        <div>
          <div className={styles.inputWrapper}>
            <div className={styles.borderWrapper}>
              <input
                type="text"
                value={phoneNumber["phone"]}
                className={styles.borderItem}
                placeholder="手机号"
                onChange={(event) => {
                  const phone = event.target.value;
                  setPhoneNumber((p) => phone);
                }}
                onClick={onClickInput}
              />
            </div>
          </div>
          <div className={styles.hint}>{hint}</div>
          <div className={styles.action}>
            <div className={styles.btn} onClick={handleSendPhone}>
              获取验证码
            </div>
          </div>
        </div>
      ) : (
        <div>
          <div className={styles.inputWrapper}>
            <div className={styles.borderWrapper}>
              <input
                type="text"
                value={code}
                className={styles.borderItem}
                placeholder="验证码"
                onChange={(event) => {
                  const code = event.target.value;
                  setCode((c) => code);
                }}
                onClick={onClickInput}
              />
            </div>
          </div>
          <div className={styles.hint}>{hint}</div>
          <div className={styles.action}>
            <div className={styles.btn} onClick={handleVerify}>
              确认验证码
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default withRouter(Index);
